package com.example.scenictourback.service.impl;

import com.example.scenictourback.dto.UserDTO;
import com.example.scenictourback.entity.User;
import com.example.scenictourback.repository.OrderRepository;
import com.example.scenictourback.repository.UserRepository;
import com.example.scenictourback.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public List<UserDTO> listAllUsers() {
        List<User> users = userRepository.findAll();
        return users.stream()
                .map(UserDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public UserDTO getUserById(Integer id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        return UserDTO.fromEntity(user);
    }

    @Override
    @Transactional
    public UserDTO updateUser(Integer id, User user) {
        User existingUser = userRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        // 如果提供了新密码，则加密后更新
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        
        // 更新其他信息
        if (user.getPhone() != null) {
            existingUser.setPhone(user.getPhone());
        }
        
        if (user.getRole() != null) {
            existingUser.setRole(user.getRole());
        }
        
        if (user.getStatus() != null) {
            existingUser.setStatus(user.getStatus());
        }
        
        User updatedUser = userRepository.save(existingUser);
        return UserDTO.fromEntity(updatedUser);
    }

    @Override
    @Transactional
    public UserDTO updateUserStatus(Integer id, Integer status) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        user.setStatus(status);
        User updatedUser = userRepository.save(user);
        
        return UserDTO.fromEntity(updatedUser);
    }

    @Override
    @Transactional
    public void deleteUser(Integer id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        // 检查用户是否有关联订单
        long orderCount = orderRepository.findByUserId(id).size();
        if (orderCount > 0) {
            throw new IllegalStateException("该用户有关联订单，无法删除");
        }
        
        userRepository.deleteById(id);
    }

    @Override
    public Map<String, Object> getUserStats() {
        Map<String, Object> stats = new HashMap<>();
        List<User> allUsers = userRepository.findAll();
        
        // 用户总数
        stats.put("totalUsers", allUsers.size());
        
        // 用户角色统计
        Map<Integer, Long> roleStats = allUsers.stream()
                .collect(Collectors.groupingBy(User::getRole, Collectors.counting()));
        stats.put("roleStats", roleStats);
        
        // 用户状态统计
        Map<Integer, Long> statusStats = allUsers.stream()
                .collect(Collectors.groupingBy(User::getStatus, Collectors.counting()));
        stats.put("statusStats", statusStats);
        
        return stats;
    }
} 